package xyz.scootaloo.mono.admin.service.auth

import cn.hutool.core.lang.Assert
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import xyz.scootaloo.mono.admin.dto.PageInfo
import xyz.scootaloo.mono.admin.dto.QuickUserFormVO
import xyz.scootaloo.mono.admin.dto.SysUserVO
import xyz.scootaloo.mono.admin.dto.UpdateUserFormVO
import xyz.scootaloo.mono.base.exception.MonoIllegalArgumentException
import xyz.scootaloo.mono.data.cache.RoleCacheManager
import xyz.scootaloo.mono.data.service.AuthService
import xyz.scootaloo.mono.security.service.AccountService
import javax.servlet.http.HttpServletRequest

/**
 * @author flutterdash@qq.com
 * @since 2021/9/1 8:53
 */
@Service
class UserManageService {

    @Autowired private lateinit var authService: AuthService
    @Autowired private lateinit var accountService: AccountService

    /**
     * 对用户列表进行分页
     *
     * 前端页面显示以1为开始起始页面, 后端数据库偏移量从0开始计算, 所以这个对[pageNum]进行减一处理
     *
     * @param pageNum 前端页面的编号
     * @param pageSize 页面内容数量
     */
    fun list(pageNum: Int, pageSize: Int): PageInfo<SysUserVO> =
        PageInfo(
            authService.getUserTableRecordCount(), pageNum, pageSize,
            authService.listUsers(pageNum - 1, pageSize).map(SysUserVO::of)
        )

    fun search(name: String): List<SysUserVO> {
        val authUser = authService.findAuthUserByName(name)
        return if (authUser != null) {
            listOf(SysUserVO.of(authUser))
        } else {
            emptyList()
        }
    }

    fun create(form: QuickUserFormVO, request: HttpServletRequest) {
        val count = authService.addAuthUser(request, form.fillAndToAuthUser())
        Assert.isTrue(count > 0, "增加用户失败, 用户名=${form.username}")
    }

    fun delete(uid: Int, request: HttpServletRequest) {
        val client = accountService.getCurrentClient()
        Assert.isTrue(client.uid != uid, "不能删除自己的账号")

        val count = authService.deleteAuthUserByUid(request, uid)
        Assert.isTrue(count > 0, "删除用户失败, 用户ID=$uid")
    }

    fun disable(uid: Int, request: HttpServletRequest) {
        val count = authService.updateUserStatus(request, uid, 3)
        Assert.isTrue(count > 0, "禁用用户账号失败, 用户ID=$uid")
    }

    fun distributeRoles(uid: Int, roles: List<Int>, request: HttpServletRequest) {
        val roleCode = roles.sum()
        if (RoleCacheManager.list(roleCode).isEmpty()) throw MonoIllegalArgumentException("系统中不存在此角色编号")
        val count = authService.updateUserRoleCode(request, uid, roleCode)
        Assert.isTrue(count > 0, "更新用户角色代码失败, $roleCode")
    }

    fun updateInfo(user: UpdateUserFormVO) {
        val count = authService.updateUserInfo(user.toAuthUser())
        Assert.isTrue(count > 0, "更新用户信息失败, 用户账号=${user.username}")
    }

    fun getInfo(uid: Int): UpdateUserFormVO {
        val user = authService.findAuthUserByUid(uid)
        Assert.isTrue(user != null, "未查找到`uid`为${uid}的用户")
        return UpdateUserFormVO.of(user!!)
    }

}
